Accessing Key Vault in Azure Function

Azure Key Vault is a secure storage for keys connection strings and password. Azure Key Vault helps safeguard cryptographic keys and secrets used by cloud applications and services. By using Key Vault, you can encrypt keys and secrets (such as authentication keys, storage account keys, data encryption keys, .PFX files, and passwords) using keys protected by hardware security modules (HSMs).

Key Vault streamlines the key management process and enables you to maintain control of keys that access and encrypt your data. Developers can create keys for development and testing in minutes, and then seamlessly migrate them to production keys. Security administrators can grant (and revoke) permission to keys, as needed. More details about this can be found on https://docs.microsoft.com/en-us/azure/key-vault/key-vault-whatis

Below I will be discussing what all are the steps to access Key vault from Azure function.

Steps to Access key vault

  • Create an Azure Key vault as below

1

  • Create a key vault secret as below

2

3

  • Write an Azure Function code as below
[FunctionName(“GetKeyVaultValues”)]

public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, “get”, “post”, Route = null)]HttpRequestMessage req, TraceWriter log)

{

log.Info(“C# HTTP trigger function processed a request.”);

string linkKeyVaultUrl = $”https://keyvaultaccess.vault.azure.net/secrets/&#8221;;

string keyvaultKey = $”KeyVaultKey”;

var secretURL = linkKeyVaultUrl + keyvaultKey;

 

var azureServiceTokenProvider = new AzureServiceTokenProvider();

var kvClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

try

{

var clientIdRecord = await kvClient.GetSecretAsync(secretURL).ConfigureAwait(false);

string KeyvaultValue = clientIdRecord.Value;

return req.CreateErrorResponse(HttpStatusCode.OK, “Key vault secret value is  :  ” + KeyvaultValue);

}

catch (System.Exception ex)

{

 

return req.CreateResponse(HttpStatusCode.BadRequest, “Key vault value request is not successfull”);

}

}

  • The nuget packages used in this code are as follows
    • Microsoft.Azure.KeyVault
    • Microsoft.Azure.Services.AppAuthentication
  • publish the Azure function as below

4

  • Go to the platform feature for the application and set the managed identity as On

5

  • Go to the Azure Key Vault
  • Add the application to access policy as shown below.

6

 

7

  • Set the Key and Secret permission as below

8

Now you can go to “Postman” and call the method to get the key vault value and use wherever required

9

 

 

 

 

Leave a comment